package com.now.printer.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.now.printer.R;
import com.now.printer.base.BaseActivity2;
import com.now.printer.base.x5.FileReaderView;
import com.now.printer.db.RecentlyTable;
import com.now.printer.http.Xutils;
import com.now.printer.idcardcamera.camera.CameraActivity;
import com.now.printer.idcardcamera.cropper.CropImageView;
import com.now.printer.idcardcamera.cropper.CropListener;
import com.now.printer.print.PDFCheck;
import com.now.printer.utils.ConvertUtils;
import com.now.printer.utils.DbUtils;
import com.now.printer.utils.FileUtils;
import com.now.printer.utils.FileUtils2;
import com.now.printer.utils.PrinterUtils;
import com.now.printer.utils.convert_html.ExcelToHtml;
import com.xuexiang.xaop.annotation.Permission;
import com.xuexiang.xutil.display.ImageUtils;
import com.xuexiang.xutil.tip.ToastUtils;

import org.xutils.DbManager;
import org.xutils.common.util.DensityUtil;
import org.xutils.common.util.LogUtil;
import org.xutils.ex.DbException;
import org.xutils.image.ImageOptions;
import org.xutils.x;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.xuexiang.xaop.consts.PermissionConsts.STORAGE;

/**
 * 预览和打印
 * Created by xudong on 2021/5/18.
 */
public class FilePreviewAndPrintActivity_backup extends BaseActivity2 {

    public final static String INTENT_KEY_ID_CARD_FRONT_BACK = "INTENT_KEY_ID_CARD_FRONT_BACK";


    public final static String INTENT_KEY_FILE_URI = "INTENT_KEY_FILE_URI";
    public final static String INTENT_KEY_FILE_NAME = "INTENT_KEY_FILE_NAME";
    public final static String INTENT_KEY_FILE_IMAGE = "INTENT_KEY_FILE_IMAGE";
    public final static String INTENT_KEY_FILE_LAST_TIME = "INTENT_KEY_FILE_LAST_TIME";
    public final static String INTENT_KEY_FILE_SIZE = "INTENT_KEY_FILE_SIZE";

    private FileReaderView fileReaderView;
    private int fileImage;
    private String fileUri = "", fileLastTime, fileSize, fileName;
    private Button btnPrint;

    private ImageView image, image2;

    private String[] frontAndBackImagePath = null;

    private CropImageView mCropImageView1, mCropImageView2;


    public int getLayoutId() {
        return R.layout.activity_file_webview;
    }

    public void doBusiness(Context mContext) {

        initView();
        fileUri = getIntent().getStringExtra(INTENT_KEY_FILE_URI);
        LogUtil.i("预览页面获取file url is : " + fileUri);

        fileName = getIntent().getStringExtra(INTENT_KEY_FILE_NAME);
        fileImage = getIntent().getIntExtra(INTENT_KEY_FILE_IMAGE, -1);
        fileLastTime = getIntent().getStringExtra(INTENT_KEY_FILE_LAST_TIME);
        fileSize = getIntent().getStringExtra(INTENT_KEY_FILE_SIZE);

        fileReaderView = (FileReaderView) findViewById(R.id.file_reader_view);
        image = findViewById(R.id.image);
        image2 = findViewById(R.id.image2);
        mCropImageView1 = findViewById(R.id.crop_image_view);
        mCropImageView2 = findViewById(R.id.crop_image_view2);
        //获取身份证
        frontAndBackImagePath = getIntent().getStringArrayExtra(CameraActivity.INTENT_KEY_ID_CARD_FRONT_BACK);

        String action = getIntent().getAction();
        //通过第三方应用打开到这里
        openThisActivityByOtherApp(action);
        //文件uri是个图片地址
        if (FileUtils.isPicFile(fileUri)) {
            image.setVisibility(View.VISIBLE);
            fileReaderView.setVisibility(View.GONE);
            x.image().bind(image, new File(fileUri).toURI().toString(), new ImageOptions.Builder()
//                    .setSize(DensityUtil.dip2px(120), DensityUtil.dip2px(120))
                    .setRadius(DensityUtil.dip2px(5))
                    // 如果ImageView的大小不是定义为wrap_content, 不要crop.
//                    .setCrop(true) // 很多时候设置了合适的scaleType也不需要它.
                    // 加载中或错误图片的ScaleType
                    //.setPlaceholderScaleType(ImageView.ScaleType.MATRIX)
                    .setImageScaleType(ImageView.ScaleType.FIT_CENTER)
                    .setLoadingDrawableId(R.mipmap.ic_launcher)
                    .setFailureDrawableId(R.mipmap.ic_launcher)
                    .setIgnoreGif(false)
                    .build());
        } else {
            //证件照的uri
            if (frontAndBackImagePath != null) {

                image.setVisibility(View.VISIBLE);
                image2.setVisibility(View.VISIBLE);

                mCropImageView1.setVisibility(View.VISIBLE);
                mCropImageView2.setVisibility(View.VISIBLE);

                float idCardScale = (float) 240 / 151;
                int idCardWidth = DensityUtil.getScreenWidth();
                int idCardHeight = (int) (idCardWidth / idCardScale);
                RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mCropImageView1.getLayoutParams();
                layoutParams.width = idCardWidth;
                layoutParams.height = idCardHeight;
                mCropImageView1.setLayoutParams(layoutParams);
                RelativeLayout.LayoutParams layoutParams2 = (RelativeLayout.LayoutParams) mCropImageView2.getLayoutParams();
                layoutParams2.width = idCardWidth;
                layoutParams2.height = idCardHeight;
                mCropImageView2.setLayoutParams(layoutParams2);

                LogUtil.i("屏幕宽： " + DensityUtil.getScreenWidth() + " \t 身份证高：" + idCardHeight);
                x.image().bind(image, new File(frontAndBackImagePath[0]).toURI().toString(), new ImageOptions.Builder()
                        .setSize(111, 70)
                        .setImageScaleType(ImageView.ScaleType.FIT_CENTER)
                        .setLoadingDrawableId(R.mipmap.ic_launcher)
                        .setFailureDrawableId(R.mipmap.ic_launcher)
                        .setIgnoreGif(false)
                        .build());
                x.image().bind(image2, new File(frontAndBackImagePath[1]).toURI().toString(), new ImageOptions.Builder()
                        .setSize(111, 70)
                        .setImageScaleType(ImageView.ScaleType.FIT_CENTER)
                        .setLoadingDrawableId(R.mipmap.ic_launcher)
                        .setFailureDrawableId(R.mipmap.ic_launcher)
                        .setIgnoreGif(false)
                        .build());

                mCropImageView1.setImageBitmap(ImageUtils.getBitmap(new File(frontAndBackImagePath[0])));
                mCropImageView2.setImageBitmap(ImageUtils.getBitmap(new File(frontAndBackImagePath[1])));

                return;
            } else {
                //普通文件地址
                image2.setVisibility(View.GONE);
            }
            image.setVisibility(View.GONE);
            fileReaderView.setVisibility(View.VISIBLE);
            openFile(fileUri);
        }
    }

    private void initView() {
        btnPrint = findViewById(R.id.btn_print);
        btnPrint.setOnClickListener(onClickListener);
    }

    //通过第三方应用打开到这里
    private void openThisActivityByOtherApp(String action) {
        if (Intent.ACTION_VIEW.equals(action)) {
            LogUtil.d("处理编码前" + getIntent().getDataString());

            Uri uri = getIntent().getData();
            fileUri = Uri.decode(uri.getEncodedPath());
            LogUtil.d("uri is ：" + uri);
            LogUtil.d("处理编码后的地址是：" + fileUri);
            String getFPUri = FileUtils2.getFPUriToPath(this, uri);
            if (TextUtils.isEmpty(getFPUri)) {
                getFPUri = FileUtils2.getFPUriToPath(this, Uri.fromFile(new File(fileUri)));
                if (TextUtils.isEmpty(getFPUri)) {
                    getFPUri = FileUtils2.getFileFromUri(this, uri);
                    if (TextUtils.isEmpty(getFPUri)) {
                        if (fileUri.startsWith("/external")) {
                            fileUri = fileUri.replaceAll("/external", "/storage/emulated/0");
                        } else if (fileUri.startsWith("/external_files")) {
                            fileUri = fileUri.replaceAll("/external_files", "");
                        }
                    }
                }
            }
            fileUri = getFPUri;
            LogUtil.d("终极处理后：" + fileUri);
        } else if (Intent.ACTION_SEND.equals(action)) {
            Uri uri = getIntent().getParcelableExtra(Intent.EXTRA_STREAM);
            fileUri = Uri.decode(uri.getEncodedPath());
            LogUtil.d("ACTION_SEND 接收URI：" + uri);
            LogUtil.d("ACTION_SEND 编码后：" + fileUri);

            String getFPUri = FileUtils2.getFPUriToPath(this, Uri.fromFile(new File(fileUri)));
            if (TextUtils.isEmpty(getFPUri)) {
                getFPUri = FileUtils2.getFPUriToPath(this, uri);

                if (TextUtils.isEmpty(getFPUri)) {
                    getFPUri = FileUtils2.getFileFromUri(this, uri);

                }
            }
            fileUri = getFPUri;
            LogUtil.d("ACTION_SEND 最终编码：" + fileUri);
            return;
        }
    }

    private View.OnClickListener onClickListener = v -> {
        switch (v.getId()) {
            case R.id.btn_print:
                String outputPath = fileUri + ".pdf";

                if (!TextUtils.isEmpty(fileUri)) {
                    if (fileUri.endsWith(".pdf")) {
                        PrinterUtils.doPrint(this, fileUri);
                        return;
                    }
                    if (FileUtils.isExists(outputPath)) {
                        if (!PDFCheck.check(outputPath)) {
                            File file = new File(outputPath);
                            if (file.delete()) {
                                ToastUtils.toast("请重新点击打印");
                            }
                            return;
                        }
//                        PrinterUtils.doPrint(this, outputPath);
//                        return;
                    }

                    if (fileUri.endsWith(".doc") || fileUri.endsWith(".docx")) {

                        //param1: 源文件  params2:   pdf 路径
//                        WordToHtml wordToHtml = new WordToHtml(this,fileUri, new File(FileUtils.getCurrentAppPath(this)));
//                        String html = wordToHtml.getContent();
//
//                        LogUtil.i("word转HTML为： " + html);
//                        ConvertUtils.convertHtmlToPdf(FilePreviewAndPrintActivity.this,html);

//                                ConvertUtils.convertWordToPdf(fileUri, finalOutputPath5);
//                                Message message = new Message();
//                                message.what = 1;
//                                message.obj = finalOutputPath5;
//                                handler.sendMessage(message);

                    } else if (fileUri.endsWith(".ppt") || fileUri.endsWith(".pptx")) {

                        String finalOutputPath = outputPath;
                        x.task().run(new Runnable() {
                            @Override
                            public void run() {

//                                ConvertUtils.convertPptToPdf(fileUri, finalOutputPath);
                                Message message = new Message();
                                message.what = 1;
                                message.obj = finalOutputPath;
                                handler.sendMessage(message);
                            }
                        });

                    } else if (fileUri.endsWith(".xls") || fileUri.endsWith(".xlsx")) {

                        String finalOutputPath3 = outputPath;
//                      ConvertUtils.convertExcelToPdf(fileUri, finalOutputPath3);

                        String html = ExcelToHtml.readExcelToHtml(fileUri);
                        ConvertUtils.convertHtmlToPdf(FilePreviewAndPrintActivity_backup.this, html);
                        LogUtil.i("Excel to html结果是： " + html);
//                                Message message = new Message();
//                                message.what = 1;
//                                message.obj = finalOutputPath3;
//                                handler.sendMessage(message);

                    } else if (fileUri.endsWith(".jpg") || fileUri.endsWith(".jpeg") || fileUri.endsWith(".png")) {
                        String finalOutputPath1 = outputPath;
                        x.task().run(new Runnable() {
                            @Override
                            public void run() {
                                ConvertUtils.convertImageToPdf(FilePreviewAndPrintActivity_backup.this, fileUri, finalOutputPath1);
                                Message message = new Message();
                                message.what = 1;
                                message.obj = finalOutputPath1;
                                handler.sendMessage(message);
                            }
                        });

                    } else if (fileUri.endsWith(".txt")) {

                        String finalOutputPath4 = outputPath;
                        x.task().run(new Runnable() {
                            @Override
                            public void run() {
                                ConvertUtils.convertTextToPdf(fileUri, finalOutputPath4);

                                Message message = new Message();
                                message.what = 1;
                                message.obj = finalOutputPath4;
                                handler.sendMessage(message);
                            }
                        });
                    }
                } else {
                    setCropFrontAndBack();
                    outputPath = FileUtils.getCurrentAppPath(this) + File.separator + "证件照.pdf";
                    //为证件照设计
                    if (frontAndBackImagePath != null && TextUtils.isEmpty(fileUri)) {
                        String finalOutputPath2 = outputPath;
                        x.task().run(new Runnable() {
                            @Override
                            public void run() {
                                ConvertUtils.convertImageToPdf(FilePreviewAndPrintActivity_backup.this, frontAndBackImagePath, finalOutputPath2);
                                Message message = new Message();
                                message.what = 1;
                                message.obj = finalOutputPath2;
                                handler.sendMessage(message);
                            }
                        });
                    }
                }

//                PrinterUtils.doPrint(this, outputPath);
                saveCurrentFileToDatabase(fileUri);
                break;
        }
    };

    private boolean cropFront = false;
    private boolean cropBack = false;

    private void setCropFrontAndBack() {
        /*手动裁剪图片*/
        mCropImageView1.crop(new CropListener() {
            @Override
            public void onFinish(Bitmap bitmap) {
                if (bitmap == null) {
                    Toast.makeText(getApplicationContext(), getString(R.string.crop_fail), Toast.LENGTH_SHORT).show();
                    finish();
                    cropFront = false;
                }
                /*保存图片到sdcard并返回图片路径*/
                String imagePath = FileUtils.getCurrentAppPath(FilePreviewAndPrintActivity_backup.this)
                        + File.separator
                        + System.currentTimeMillis() + ".jpg";
                if (ImageUtils.save(bitmap, imagePath, Bitmap.CompressFormat.JPEG)) {
                    cropFront = true;
                    frontAndBackImagePath[0] = imagePath;
                }
            }
        }, true);
        /*手动裁剪图片*/
        mCropImageView2.crop(new CropListener() {
            @Override
            public void onFinish(Bitmap bitmap) {
                if (bitmap == null) {
                    Toast.makeText(getApplicationContext(), getString(R.string.crop_fail), Toast.LENGTH_SHORT).show();
                    finish();
                    cropBack = false;
                }
                /*保存图片到sdcard并返回图片路径*/
                String imagePath = FileUtils.getCurrentAppPath(FilePreviewAndPrintActivity_backup.this)
                        + File.separator
                        + System.currentTimeMillis() + ".jpg";
                if (com.now.printer.idcardcamera.utils.ImageUtils.save(bitmap, imagePath, Bitmap.CompressFormat.JPEG)) {
                    cropBack = true;
                    frontAndBackImagePath[1] = imagePath;
                }
            }
        }, true);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                PrinterUtils.doPrint(FilePreviewAndPrintActivity_backup.this, (String) msg.obj);
            }
        }
    };

    /**
     * 打开文件
     *
     * @param fileUri
     */
    @Permission(STORAGE)
    private void openFile(String fileUri) {
        if (!TextUtils.isEmpty(fileUri)) {
            fileReaderView.show(fileUri);
        } else {
            ToastUtils.toast("文件路径无效！");
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        if (fileReaderView != null) {
            fileReaderView.stop();
        }
        super.onDestroy();
    }


    //打印完毕后保存当前文档
    private void saveCurrentFileToDatabase(String filePath) {
        x.task().run(new Runnable() {
            @Override
            public void run() {
                try {
                    DbManager db = x.getDb(DbUtils.daoConfig);

                    List<RecentlyTable> recentlyTableList = db.selector(RecentlyTable.class).findAll();

                    RecentlyTable recentlyTable = new RecentlyTable();
                    recentlyTable.setPath(filePath);
                    recentlyTable.setName(fileName);
                    recentlyTable.setImageId(fileImage);

                    if (recentlyTableList == null) {
                        recentlyTable.setIsCollected("false");
                    }

                    recentlyTable.setSize(fileSize);
                    recentlyTable.setLastTime(fileLastTime);
                    db.saveOrUpdate(recentlyTable);

                } catch (DbException e) {
                    e.printStackTrace();
                    LogUtil.i("saveCurrentFileToDatabase DbException：" + e.getMessage());

                }
            }
        });

    }


}
